<template>
	<view style="overflow-x: hidden;position: relative;">
		<u-upload
			:disabled="disabled"
			:deletable="!disabled"
			:accept="accept"
			:fileList="fileList1" 
			@afterRead="afterRead" 
			@delete="deletePic" 
			name="1"
			v-bind="$attrs"
		>
		</u-upload>
		<view  style="position: absolute;top: -999999px;">
		  <view><canvas canvas-id="myCanvas" style="width: 1000px;height: 1000px;visibility: hidden;"></canvas></view>
		</view>
	</view>
</template>

<script>
	import { fileUpload,getImgByFileNo } from "@/api/system/common"
	import { mapGetters } from 'vuex'
	export default {
		props:{
			value:{
				type:[String,Array]
			},
			accept:{
				type:String,
				default:'image'
			},
			disabled:Boolean,
			watermark:{
				type:Boolean,
				default:false
			}
		},
		data() {
			return {
				fileList1: [],
				isInit:false,
				chooseImage:false
			}
		},
		watch:{
			value:{
				handler(){
					// 手动选择图片不触发图片初始化请求
					if(this.chooseImage !== true){
						this.init(this.value)
					}else{
						this.chooseImage = false
					}
				},
				immediate:true
			}
		},
		computed:{
			...mapGetters(['userInfo']),
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 增加水印
				if(this.watermark){
					uni.showLoading({
						 title: "处理中...",
						 mask: false
					});
					let data = await this.getWatermark(event.index,event.file.url);
					event.file.url = data;
					event.file.thumb = data;
					uni.hideLoading();
				}
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				const newFile = []
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.fileNo
					}))
					fileListLen++
					newFile.push(result.fileNo)
				}
				this.setFileList(event)
				this.chooseImage = true
				const fileList = this.value instanceof Array?this.value:this.value?this.value.split(','):[]
				this.$emit('change',this.value instanceof Array ? fileList.concat(newFile):fileList.concat(newFile).join(','))
			},
			setFileList(event){ // 选择图片后处理显示预览问题
				this[`fileList${event.name}`].forEach(item => {
					item.url = item.thumb
				})
				this.fileList1 = this[`fileList${event.name}`]
			},
			uploadFilePromise(url) {
				return new Promise( async(resolve, reject) => {
					const fileRes = await fileUpload(url)
					if(!fileRes.data.success){
						return uni.showToast({ title: fileRes.data.message, icon: 'success' })
					}
					resolve(fileRes.data.result)
				})
			},
			init(list){
				let fileNoList = list instanceof Array?list:list?list.split(','):[]
				const fileList = []
				if(this.accept === 'image'){
					if(fileNoList.length <=0){
						return
					}
					const axiosList = []
					fileNoList.forEach((fileNo)  => {
						axiosList.push(getImgByFileNo(fileNo))
					})
					Promise.all(axiosList).then((rspList) => {
						rspList.forEach((url, i) => {
							fileList.push({
								message: '',
								name:'file',
								"type": "image",
								status: "success",
								url: url,
								thumb: url // base64图片
							})
						})
						this.fileList1 = fileList
					})
				}else{
					fileNoList.forEach(item => {
						fileList.push({
							message: '',
							name:item ,
							status: "success",
							url: item,
							thumb: item // base64图片
						})
					})
					this.fileList1 = fileList
				}
				this.isInit = true
			},
			getWatermark(index, list){
			    return new Promise((resolve, reject) => {
			        var that = this;
			        uni.getImageInfo({
			            src: list,
			            success: (ress) => {
			              let ctx = uni.createCanvasContext('myCanvas'); //创建画布
			                //将图片src放到cancas内，宽高为图片大小
			              ctx.drawImage(list, 0, 0, ress.width / 3, ress.height / 3)
			              let textToWidth = ress.width / 3 * 0.03;  //字体宽度
			              let textToHeight = ress.height / 3; //字体高度
										ctx.setFontSize(20);
										ctx.setGlobalAlpha(0.5);
			                //根据需求，自行设置
			              that.lineFeed(`拍摄：${that.userInfo.nickname}`, textToWidth, textToHeight * 0.8,ress.width / 3 * 0.9,ctx)
			              that.lineFeed(`时间：${uni.$u.timeFormat(new Date, 'yyyy-mm-dd hh:MM:ss')}`, textToWidth, textToHeight * 0.85,ress.width / 3 * 0.9,ctx)	      
										ctx.draw(false,()=>{
											setTimeout(() => {//制作水印需要时间，这里最好设置定时
												uni.canvasToTempFilePath({//内容转成图片
													width: ress.width / 3,    // 画布宽度
													height: ress.height / 3,    // 画布高度
													canvasId: 'myCanvas',
													success: (res) => {
														// list = res.tempFilePath
														// resolve(list);
														uni.compressImage({
														  src: res.tempFilePath,
														  quality: 80,
														  success: res2 => {
																list = res2.tempFilePath
																resolve(list);
														    console.log(res2.tempFilePath)
														  }
														})
														
													}
												})
											}, 500)
										});
			            }
			        })
			    })
			},
			lineFeed(a,x,y,w,context){
				let chr = a.split("");
				let temp = "";                
				let row = [];
				
				context.font = 'normal bold 16px Arial,sans-serif '
				context.setFillStyle('#FFA500') //字体颜色
				
				for(let i = 0; i < chr.length; i++){
						if( context.measureText(temp).width < w ){
								;
						}
						else{
								row.push(temp);
								temp = "";
						}
						temp += chr[i];
				}
				
				row.push(temp);
				
				for(let r = 0; r < row.length; r++){
					context.fillText(row[r],x,y+(r+1)*20);
				}
			}
		},
		mounted() {
			// this.init(this.value)
		},
		model: {
			prop: 'value',
			event: 'change'
		}
	}
</script>